package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
public class GiteeBindController {


    @Autowired
    UserMapper userMapper;

    @RequestMapping("/callbackCode.do")
    public String callback(String code, HttpServletRequest request,HttpServletResponse response,Model model){
        System.out.println("接收到的临时授权码 " + code);
        // 根据code获取 token
        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token " + tokenByCode);
        // 根据token 获取 gitee用户账号信息
        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);

        System.out.println("获取到的gitee账号信息" + JSON.toJSONString(userInfoByToken));
        // 不需要获取个人空间地址充当用户名了，因为 本地已经有用户存在了
        String nickName = userInfoByToken.getString("name");
        Integer giteeId = userInfoByToken.getInteger("id");
        String avatarUrl = userInfoByToken.getString("avatar_url");

        // 获取当前登录的账号 张三
        // 从request中获取cookie， 再从cookie中过滤出 token  再解密这个token 得到用户信息
        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        userFromRequest.setAvatarUrl(avatarUrl);
        userFromRequest.setNickName(nickName);
        userFromRequest.setGiteeId(giteeId);
        userMapper.updateUserById(userFromRequest);
        //重新制作 学生证 ，重新加密用户得到token  把token放入cookie  把cookie返回给浏览器
        TokenUtils.responseTokenByCookie(userFromRequest,response);

        model.addAttribute("nickName",nickName);
        model.addAttribute("avatarUrl",avatarUrl);
        model.addAttribute("msg","绑定成功");
        return "success";
    }
}
